<?php

namespace App\Http\Controllers\Miniapp;

use App\Http\Controllers\Controller;
use App\Models\miniapp\Goods;

class GoodsController extends Controller
{
    /**
     * 获取商品列表
     *
     * @param int $cid      0
     * @param int $page     1
     * @param int $limit    10
     *
     * @return object
     */
    public function index()
    {
        $cid = request('cid', 0);
        $page = request('page', 1);
        $limit = request('limit', 10);

        $list = Goods::select('id', 'cid', 'title', 'image', 'price')
            ->with('category:id,name')
            ->when($cid, function ($query) use ($cid) {
                return $query->where(compact('cid'));
            })
            ->where('is_sale', 1)
            ->latest();

        $data = $this->getPaginate($list, $page, $limit);
        return $this->successful($data);
    }

    /**
     * 小程序首页推荐商品列表
     * @return object
     */
    public function recommendList()
    {
        $goods = Goods::select('id', 'title', 'image', 'price')
            ->where('is_recommend', 1)
            ->where('is_sale', 1)
            ->get();
        return $this->successful($goods);
    }

    /**
     * 小程序商品详情
     *
     * @param int $id 商品id
     *
     * @return object
     */
    public function show($id)
    {
        $goods = Goods::with('category:id,name')
            ->where('is_sale', 1)
            ->find($id);

        if (!$goods) {
            return $this->fail('商品不存在或已下架');
        }

        return $this->successful($goods);
    }
}
